package apigateway.project.core.filter.loadbalance;

import apigateway.project.commen.config.ServiceInstance;
import apigateway.project.core.CacheConfig;
import apigateway.project.core.context.GlobalContext;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Set;

/**
 * 提供通过散列表来分配后端服务的负载均衡算法
 * 适用于会话保持，确保每次客户端连接到同一个服务器
 */
@Slf4j
public class IPHashLoadBalanceRule implements LoadBalanceGatewayRule{
    @Override
    @Deprecated
    public ServiceInstance choose(String serviceName) {
        return null;
    }

    @Override
    public ServiceInstance choose(GlobalContext ctx) {
        //获取服务实例集合
        Set<ServiceInstance> serviceInstanceSet = CacheConfig.getCacheConfig().getServiceByServiceName(ctx.getRule().getServiceName());
        ArrayList<ServiceInstance> serviceInstances = new ArrayList<>(serviceInstanceSet);
        // 哈希计算客户端的ip来请求的服务器
        int index = ctx.getRequest().getClientIp().hashCode() % serviceInstances.size();
        ServiceInstance instance = serviceInstances.get(index);
        return instance;
    }
}
